using CGF;
using UnityEngine;

public class BtnSendCode : MonoBehaviour
{
    protected string CacheKey = "";
    private CButton btn;
    private int endTime
    {
        get { return PlayerPrefs.GetInt(CacheKey, 0); }
        set { PlayerPrefs.SetInt(CacheKey, value); }
    }
    private float timer;

    public virtual void Awake()
    {
        btn = GetComponent<CButton>();
    }

    private void OnEnable()
    {
        int remainTime = endTime - TimeHelper.GetLocalTimestampS();
        btn.enabled = remainTime <= 0;
        btn.text.text = btn.enabled ? CommAssets.instance.I18N_send_code : remainTime + "s";
    }

    public void StartTimer()
    {
        btn.text.text = "60s";
        endTime = TimeHelper.GetLocalTimestampS() + 60;
        btn.enabled = false;
    }

    void Update()
    {
        timer -= Time.deltaTime;
        if (timer < 0)
        {
            timer = 1;
            if (endTime > 0)
            {
                int remainTime = Mathf.Max(0, endTime - TimeHelper.GetLocalTimestampS());
                btn.text.text = remainTime + "s";
                if (remainTime == 0)
                {
                    endTime = 0;
                    btn.text.text = CommAssets.instance.I18N_send_code;
                    btn.enabled = true;
                }
            }
        }
    }
}
